//
//  EmoticonPackages.swift
//  emoticonKB
//
//  Created by mac on 16/3/21.
//  Copyright © 2016年 mac. All rights reserved.
//

//------------表情模型------------------

import UIKit

//表情模型 Emoticon [Emoticon1][Emoticon2][Emoticon3][Emoticon4][Emoticon5][Emoticon6]
//需要将分组表情的字典数组转换
class EmoticonPackages: NSObject {

    var name: String?
    var sectionEmoticon = [[Emoticons]]()
    //构造函数
    init(id: String,name: String,array: [[String : String]]) {
        
        super.init()
        self.name = name
        
        //遍历字典数组 获取单个字典 转换为模型
        
        var emoticons = [Emoticons]()
        
        // 每20个表情就添加一个删除模型
        var index = 0
        
        for item in array {
            
            let a = Emoticons(id: id,dict: item)
            emoticons.append(a)
            
            index++
            
            if index == 20 {
                //人为的添加一个删除按钮的模型
                let delete = Emoticons(isDelete: true)
                //添加到数组中
                emoticons.append(delete)
                //重要标志位
                index = 0
            }
        }
  
        //等待删除按钮添加完毕后 就对每一组分组表情取模 
        let delta = emoticons.count % EmoticonCount
//        print(delta)
        
        if delta == 0 {
        
            //不需要添加空表情
            let res = sectionEmoticonWithEmoticons(emoticons)
            //添加到属性数组中
            sectionEmoticon = res
            
            return
        }
        //添加空表情
        for _ in delta..<20 {
        
            // 添加空白表情
            let space = Emoticons(isEmpty: true)
            emoticons.append(space)
        }
        
        //最后再添加一个删除按钮的模型
        let delete = Emoticons(isDelete: true)
        emoticons.append(delete)
        
        let res = sectionEmoticonWithEmoticons(emoticons)
        //添加到属性数组中
        sectionEmoticon = res
        
    }
    
    //将模型数组转换为[[Emoticon]]
    private func sectionEmoticonWithEmoticons(emoticons: [Emoticons]) -> [[Emoticons]] {
    
        //确定有多少页
        let pageCount = (emoticons.count - 1) / EmoticonCount + 1
        
        //按页截取数组
        var res = [[Emoticons]]()
        
        for i in 0..<pageCount {
            
            let location = i * EmoticonCount
            
            var length = EmoticonCount
            
            //如果位置 ＋ 长度 大于数组的长度 会造成数组索引越界
            
            if location + length > emoticons.count {
            
                length = emoticons.count - location
            }
            
            //将[Emoticon] 转换为 NSArray
            let range = NSRange(location: location, length: length)
            let subArray = (emoticons as NSArray).subarrayWithRange(range) as! [Emoticons]
            
            //添加到目标数组中
            res.append(subArray)
        }
        
        return res
    }
    
}
